//
//  MUPayMethod.m
//  MUPay
//
//  Created by 胡发冬 on 16/6/2.
//  Copyright © 2016年 胡发冬. All rights reserved.
//

#import "MUPayMethod.h"


#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>

#import "WXApiRequestHandler.h"
#import "WXApi.h"
#import "payRequsestHandler.h"



#define ScreenSize [UIScreen mainScreen].bounds.size


@interface UIViewController ()



@end



static NSString *order_body;

static NSString *order_fee;

static NSString *order_no;


//static UIButton *payButton;


@implementation UIViewController (AliAndWeChatPayMethod)


-(void)MUPaywithwithviewController:(UIView *)view body:(NSString *)body Totle_fee:(NSString *)totle_fee Out_no:(NSString *)out_no{
    
    NSNotificationCenter *PayNotify = [NSNotificationCenter defaultCenter];
    [PayNotify addObserver:self selector:@selector(PayResult:) name:@"SendNotification" object:nil];
    
    
    
    order_body = body;
    
    order_fee = totle_fee;
    
    order_no = out_no;
    
    
    UIButton *payButton = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 0.0f, ScreenSize.width, ScreenSize.height)];
    
//    [payButton addTarget:self action:@selector(remomePayButton) forControlEvents:UIControlEventTouchUpInside];
    
    [payButton setBackgroundColor:[UIColor colorWithWhite:0.1 alpha:0.3]];
    
    [view addSubview:payButton];
    
    
    UIButton *alipay = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, ScreenSize.height-140,ScreenSize.width-20.0f , 60.0f)];
    
    [alipay setTitle:@"支付宝" forState:UIControlStateNormal];
    
    [alipay setBackgroundColor:[UIColor colorWithRed:0.21 green:0.65 blue:0.93 alpha:1.0]];
    
    //216593
    
    [alipay addTarget:self action:@selector(alipay) forControlEvents:UIControlEventTouchUpInside];
    
    [payButton addSubview:alipay];
    
    
    UIButton *wechatpay = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, ScreenSize.height-70,ScreenSize.width-20.0f , 60.0f)];
    
    [wechatpay setTitle:@"微信" forState:UIControlStateNormal];
    
    [wechatpay setBackgroundColor:[UIColor colorWithRed:0.21 green:0.65 blue:0.93 alpha:1.0]];
    
    [wechatpay addTarget:self action:@selector(wechatpay) forControlEvents:UIControlEventTouchUpInside];
    
    [payButton addSubview:wechatpay];
    
    
    
    
    
    
    
    
}
-(void)alipay{
    [self AliPaywithbody:order_body Totle_fee:order_fee Out_no:order_no];
}
-(void)wechatpay{
    [self WeChatPaywithbody:order_body Totle_fee:order_fee Out_no:order_no];
}

-(void)AliPaywithbody:(NSString *)body Totle_fee:(NSString *)totle_fee Out_no:(NSString *)out_no{
    //partner和seller获取失败,提示
    if ([ALI_PARTNER_ID length] == 0 ||
        [SELLER_ID length] == 0 ||
        [PRIVATE_KEY length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }

    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = ALI_PARTNER_ID;
    order.sellerID = SELLER_ID;
    order.outTradeNO = out_no; //订单ID（由商家自行制定）
    order.subject = body; //商品标题
    order.body = body; //商品描述
    order.totalFee = totle_fee; //商品价格
    order.notifyURL =  ALI_PAY_URL; //回调URL

    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showURL = @"m.alipay.com";

    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"mupay";

    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    //NSLog(@"orderSpec = %@",orderSpec);

    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(PRIVATE_KEY);
    NSString *signedString = [signer signString:orderSpec];

    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"WEB:reslut = %@",resultDic);
            NSString *notify=@"";
            if ([[NSString stringWithFormat:@"%@",resultDic] rangeOfString:@"resultStatus = 9000"].location != NSNotFound) {
                notify=@"支付成功";
            }else{
                notify=@"支付失败";
            }
            NSNotificationCenter *PayNotify = [NSNotificationCenter defaultCenter];
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:notify,@"PayResult",nil];
            [PayNotify postNotificationName:@"SendNotification" object:self userInfo:dict];
        }];
    }

}

-(void)WeChatPaywithbody:(NSString *)body Totle_fee:(NSString *)totle_fee Out_no:(NSString *)out_no{
    if ([WXApi isWXAppInstalled]) {
        
        NSString *fee= [NSString stringWithFormat:@"%f",[totle_fee floatValue]*100];
        
        
        payRequsestHandler *pay1 = [[payRequsestHandler alloc]init:body  Total_fee:fee Order_no:out_no];
        NSString *nonce_str = [pay1 getNoncestr];
        NSString *prepay_id = [pay1 getPrepayID];
        
        while (prepay_id == nil) {
        }
        // 设置时间格式
        NSDate *now = [NSDate date];
        NSTimeInterval timeInterval = [now timeIntervalSince1970];
        timeInterval = (int)timeInterval;
        NSString *timestamp = [NSString stringWithFormat:@"%.0lf",timeInterval];
        
        
        
        //调起微信支付···
        PayReq* req             = [[PayReq alloc] init];
        req.partnerId           = MCH_ID;
        req.prepayId            = prepay_id;
        req.nonceStr            = nonce_str;
        req.timeStamp           = timeInterval;
        req.package             = @"Sign=WXpay";
        
        NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
        [signParams setObject: WX_APP_ID forKey:@"appid"];
        [signParams setObject: nonce_str forKey:@"noncestr"];
        [signParams setObject: @"Sign=WXpay" forKey:@"package"];
        [signParams setObject: MCH_ID forKey:@"partnerid"];
        [signParams setObject: timestamp forKey:@"timestamp"];
        [signParams setObject: prepay_id forKey:@"prepayid"];
        
        //生成签名
        req.sign=[pay1 createMd5Sign:signParams];
        [WXApi sendReq:req];
        
        
    }else{
        UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"未检测到设备上的微信客户端" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [promptAlert show];
    }

}

- (void)PayResult:(NSNotification *)notify{
    //NSLog(@"recv bcast %d", index);
    NSDictionary *dict = [notify userInfo];
    NSString *result = [dict objectForKey:@"PayResult"];
    NSString *PayResult=@"";
    if ([result isEqualToString:@"支付成功"]) {
        PayResult = @"成功!";
    }else{
        PayResult = @"失败!";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付结果" message:PayResult delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
    
    [alert show];
    
    
    
}










@end
